import java.sql.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class ResetAdminUser {
    private static final String URL = "jdbc:mysql://db.test1.wcsbapp.com:3306/ChainUp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "0YvoGUzwhumnf2KGQvjN";
    
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            System.out.println("=== 完全重新初始化admin用户 ===");
            
            try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
                conn.setAutoCommit(false);
                
                // 1. 删除现有的admin用户相关数据
                System.out.println("1. 删除现有admin用户数据...");
                
                // 删除用户角色关联
                String deleteUserRole = "DELETE FROM sys_user_role WHERE user_id = (SELECT user_id FROM sys_user WHERE user_name = 'admin')";
                try (PreparedStatement stmt = conn.prepareStatement(deleteUserRole)) {
                    int affected = stmt.executeUpdate();
                    System.out.println("   删除用户角色关联: " + affected + " 条记录");
                }
                
                // 删除用户岗位关联
                String deleteUserPost = "DELETE FROM sys_user_post WHERE user_id = (SELECT user_id FROM sys_user WHERE user_name = 'admin')";
                try (PreparedStatement stmt = conn.prepareStatement(deleteUserPost)) {
                    int affected = stmt.executeUpdate();
                    System.out.println("   删除用户岗位关联: " + affected + " 条记录");
                }
                
                // 删除用户记录
                String deleteUser = "DELETE FROM sys_user WHERE user_name = 'admin'";
                try (PreparedStatement stmt = conn.prepareStatement(deleteUser)) {
                    int affected = stmt.executeUpdate();
                    System.out.println("   删除用户记录: " + affected + " 条记录");
                }
                
                // 2. 创建新的BCrypt密码
                System.out.println("\n2. 生成新的BCrypt密码...");
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                String newPassword = encoder.encode("admin123");
                System.out.println("   新密码哈希: " + newPassword);
                System.out.println("   密码长度: " + newPassword.length());
                
                // 验证密码编码
                boolean testMatch = encoder.matches("admin123", newPassword);
                System.out.println("   密码验证测试: " + (testMatch ? "✓ 通过" : "✗ 失败"));
                
                if (!testMatch) {
                    System.err.println("密码编码验证失败，停止操作");
                    conn.rollback();
                    return;
                }
                
                // 3. 插入新的admin用户
                System.out.println("\n3. 创建新的admin用户...");
                String insertUser = "INSERT INTO sys_user (user_id, dept_id, user_name, nick_name, user_type, email, phonenumber, sex, avatar, password, status, del_flag, login_ip, login_date, create_by, create_time, update_by, update_time, remark) VALUES (1, 103, 'admin', '若依', '00', 'ry@163.com', '15888888888', '1', '', ?, '0', '0', '127.0.0.1', NOW(), 'admin', NOW(), '', NULL, '管理员')";
                
                try (PreparedStatement stmt = conn.prepareStatement(insertUser)) {
                    stmt.setString(1, newPassword);
                    int affected = stmt.executeUpdate();
                    System.out.println("   创建用户记录: " + affected + " 条记录");
                }
                
                // 4. 设置用户角色（超级管理员）
                System.out.println("\n4. 设置用户角色...");
                String insertUserRole = "INSERT INTO sys_user_role (user_id, role_id) VALUES (1, 1)";
                try (PreparedStatement stmt = conn.prepareStatement(insertUserRole)) {
                    int affected = stmt.executeUpdate();
                    System.out.println("   设置管理员角色: " + affected + " 条记录");
                }
                
                // 5. 验证创建结果
                System.out.println("\n5. 验证用户创建结果...");
                String verifyUser = "SELECT u.user_id, u.user_name, u.nick_name, u.status, u.del_flag, LENGTH(u.password) as pwd_len, r.role_name FROM sys_user u LEFT JOIN sys_user_role ur ON u.user_id = ur.user_id LEFT JOIN sys_role r ON ur.role_id = r.role_id WHERE u.user_name = 'admin'";
                
                try (PreparedStatement stmt = conn.prepareStatement(verifyUser);
                     ResultSet rs = stmt.executeQuery()) {
                    
                    if (rs.next()) {
                        System.out.println("   ✓ 用户ID: " + rs.getLong("user_id"));
                        System.out.println("   ✓ 用户名: " + rs.getString("user_name"));
                        System.out.println("   ✓ 昵称: " + rs.getString("nick_name"));
                        System.out.println("   ✓ 状态: " + rs.getString("status"));
                        System.out.println("   ✓ 删除标志: " + rs.getString("del_flag"));
                        System.out.println("   ✓ 密码长度: " + rs.getInt("pwd_len"));
                        System.out.println("   ✓ 角色: " + rs.getString("role_name"));
                    } else {
                        System.err.println("   ✗ 验证失败：未找到创建的用户");
                        conn.rollback();
                        return;
                    }
                }
                
                // 提交事务
                conn.commit();
                System.out.println("\n=== ✓ admin用户重新初始化完成 ===");
                System.out.println("登录信息:");
                System.out.println("  地址: http://localhost:1024/");
                System.out.println("  用户名: admin");
                System.out.println("  密码: admin123");
                System.out.println("=====================================");
                
            }
            
        } catch (Exception e) {
            System.err.println("错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}